package com.malred.dao;

import com.malred.beans.Person;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.awt.print.Book;
import java.util.List;

/**
 * @author malguy-wang sir
 * @create ---
 */
@Repository
@Transactional
public class personDaoImp implements personDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void insert(Person person) {
        String sql = "insert into person(name,age) values(?,?)";
        Object[] args = {person.getName(),person.getAge()};
        try {
            jdbcTemplate.update(sql,args);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void update(Person person) {
        String sql = "update person set name=?,age=? where id=?";
        Object[] args = {person.getName(),person.getAge(),person.getId()};
        try {
            jdbcTemplate.update(sql,args);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
    }
    @Override
    public Person selectById(int id) {
        String sql = "select * from person where id = ?";
        Person p = null;
        try {
            p = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Person>(Person.class), id);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return p;
    }
    @Override
    public List<Person> showAll() {
        String sql = "select * from person";
        List<Person> list = null;
        try {
            list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Person>(Person.class));
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return list;
    }
    @Override
    public void deleteById(int id){
        String sql = "delete from person where id = ?";
        try {
            jdbcTemplate.update(sql, id);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
    }
}

